/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package blackjack;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author educacionit
 */
public class AdminDeDatos {

    private static AdminDeDatos instance = null;
    private boolean ocupado;
    private Connection conn = null;

    private AdminDeDatos() {
        try {
            conn = AdminDeDatos.createConnection();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    public static AdminDeDatos getInstance() {
        if (instance == null) {
            instance = new AdminDeDatos();
        }
        return instance;
    }

    public synchronized Connection getConnection() throws Exception {
        if (ocupado) {
            throw new Exception();
        }
        ocupado = true;
        return conn;

    }

    public void insertarUsuario(JugadorHumano player1) {
        Connection laConexion = null;
        // Define la conexion
        try {
            laConexion = this.getConnection();

            // Arma la sentencia de inserción y la ejecuta
            String laInsercion = "INSERT INTO usuarios (nombre,contrasenia,saldo) VALUES ('" + player1.getNombre() + "', '" + player1.getContrasenia() + "'," + Float.toString(player1.getSaldo()) + ")";
            Statement stmtInsercion = laConexion.createStatement();
            stmtInsercion.execute(laInsercion);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // Cierra el Statement y la Connection
                //stmtInsercion.close();
                this.releaseConnection(laConexion);
            } catch (Exception ex) {
                Logger.getLogger(AdminDeDatos.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void releaseConnection(Connection c) throws Exception {
        if (conn == c) {
            ocupado = false;
        } else {
            throw new Exception();
        }
    }

    public void actualizarBD(JugadorHumano player) {
        Connection c = null;
        try {
            c = this.getConnection();

            Statement stmt = c.createStatement();
            stmt.execute("UPDATE usuarios SET saldo = " + Float.toString(player.getSaldo())
                    + " WHERE nombre = '" + player.getNombre() + "'");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // System.out.println(AdminConecciones.getInstance());
                this.releaseConnection(c);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public boolean validarUsuario(JugadorHumano player1) {
        Connection c = null;
        boolean valido = false;
        try {
            c = this.getConnection();
            String laConsulta = "SELECT * FROM usuarios";
            Statement stmtConsulta = c.createStatement();
            ResultSet rs = stmtConsulta.executeQuery(laConsulta);

            while ((rs.next()) && (!valido)) {
                //System.out.println("Nombre: " + rs.getString("nombre") + " -- " + "Apellido: " + rs.getString("contrasenia"));
                if ((rs.getString("nombre").compareTo(player1.getNombre()) == 0) && (rs.getString("contrasenia").compareTo(player1.getContrasenia()) == 0)) {
                    valido = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                this.releaseConnection(c);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return valido;
        }
    }

    public boolean validarRegistro(JugadorHumano player1) {
        Connection c = null;
        boolean valido = true;
        try {
            c = this.getConnection();
            String laConsulta = "SELECT * FROM usuarios";
            Statement stmtConsulta = c.createStatement();
            ResultSet rs = stmtConsulta.executeQuery(laConsulta);

            while ((rs.next()) && (valido)) {
                //System.out.println("Nombre: " + rs.getString("nombre") + " -- " + "Apellido: " + rs.getString("contrasenia"));
                if ((rs.getString("nombre").compareTo(player1.getNombre()) == 0)) {
                    valido = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                this.releaseConnection(c);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return valido;
        }
    }

    public float getSaldo(JugadorHumano player1) {
        Connection c = null;
        boolean encontrado = false;
        float saldo = 0;
        try {
            c = this.getConnection();
            String laConsulta = "SELECT * FROM usuarios";
            Statement stmtConsulta = c.createStatement();
            ResultSet rs = stmtConsulta.executeQuery(laConsulta);

            while ((rs.next()) && (!encontrado)) {
                //System.out.println("Nombre: " + rs.getString("nombre") + " -- " + "Apellido: " + rs.getString("contrasenia"));
                if (rs.getString("nombre").compareTo(player1.getNombre()) == 0) {
                    saldo = rs.getFloat("saldo");
                    encontrado = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                this.releaseConnection(c);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return saldo;
        }
    }

//public static void main(String[]args){
//        try {
//            System.out.println(AdminDeDatos.createConnection());
//        } catch (Exception ex) {
//            Logger.getLogger(AdminDeDatos.class.getName()).log(Level.SEVERE, null, ex);
//        }
//}
    public static Connection createConnection() throws Exception {
        //java.util.Properties a = new java.util.Properties;

        // Establece el nombre del driver a utilizar
        String dbDriver = "com.mysql.jdbc.Driver";

        // Establece la conexion a utilizar contra la base de datos
        String dbConnString = "jdbc:mysql://localhost/blackjack";
        //String dbConnString = "jdbc:mysql://johnny.heliohost.org:2082/bjdb12_blackjack";

        // Establece el usuario de la base de datos
        String dbUser = "root";
        //String dbUser = "bjdb12_admin";

        // Establece la contraseña de la base de datos
        String dbPassword = "";
        //String dbPassword = "qwe123";

        // Establece el driver de conexion
        Class.forName(dbDriver).newInstance();

        // Retorna la conexion
        return DriverManager.getConnection(dbConnString, dbUser, dbPassword);
    }
}
